<script lang="ts" setup>
import { ref, reactive, onMounted, h } from 'vue';
import { Card, Table, Button, Input, Space, Form, message } from 'ant-design-vue';
import type { TableColumnsType } from 'ant-design-vue';
import { getFreelancerListApi, type FreelancerApi } from '#/api/core/freelancer';

interface FreelancerRecord {
  id: number | string | null;
  freelancer_id?: number | string | null;
  name: string;
  phone: string;
  email?: string;
  id_card: string;
  bank_account?: string;
  status: string;
  status_label?: string;
  task_names?: string[];
  created_at?: string;
  updated_at?: string;
}

interface PaginationData {
  current: number;
  pageSize: number;
  total: number;
  showSizeChanger: boolean;
  showQuickJumper: boolean;
  pageSizeOptions: string[];
  showTotal: (total: number, range: [number, number]) => string;
}

// 响应式数据
const loading = ref(false);
const dataSource = ref<FreelancerRecord[]>([]);

// 搜索表单
const searchForm = reactive({
  name: '',
  phone: '',
  id_card: ''
});

// 分页数据
const pagination = reactive<PaginationData>({
  current: 1,
  pageSize: 15,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  pageSizeOptions: ['10', '15', '20', '50'],
  showTotal: (total: number, range: [number, number]) => 
    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
});

const sortField = ref<'name' | 'phone' | 'status' | 'created_at'>('name');
const sortOrder = ref<'asc' | 'desc'>('asc');

// 表格列定义
const columns: TableColumnsType<FreelancerRecord> = [
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    width: 120,
    ellipsis: true,
    sorter: true,
    defaultSortOrder: 'ascend',
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone',
    width: 130,
    sorter: true,
  },
  {
    title: '身份证号',
    dataIndex: 'id_card',
    key: 'id_card',
    width: 180,
    ellipsis: true,
  },
  {
    title: '银行卡号',
    dataIndex: 'bank_account',
    key: 'bank_account',
    width: 180,
    ellipsis: true,
    customRender: ({ record }) => {
      return record.bank_account || '-';
    },
  },
  {
    title: '所在任务',
    key: 'tasks',
    width: 200,
    ellipsis: true,
    customRender: ({ record }) => {
      if (!record.task_names || record.task_names.length === 0) {
        return h('span', { class: 'text-gray-400' }, '暂无任务');
      }
      
      return h('div', { 
        class: 'overflow-hidden',
        title: record.task_names.join(', ')
      }, record.task_names.join(', '));
    },
  },
  {
    title: '报名状态',
    dataIndex: 'status',
    key: 'status',
    width: 120,
    sorter: true,
    customRender: ({ record }) => record.status_label || record.status || '-',
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 160,
    sorter: true,
    customRender: ({ text }) => {
      return new Date(text).toLocaleString('zh-CN');
    },
  },
];

// 获取列表数据
const fetchData = async () => {
  try {
    loading.value = true;
    
    const params = {
      page: pagination.current,
      per_page: pagination.pageSize,
      name: searchForm.name.trim() || undefined,
      phone: searchForm.phone.trim() || undefined,
      id_card: searchForm.id_card.trim() || undefined,
      sort_by: sortField.value,
      sort_order: sortOrder.value,
    };
    
    console.log('📤 发送请求参数:', params);
    
    const response = await getFreelancerListApi(params);
    console.log('📥 API响应:', response);
    
    dataSource.value = response.data || [];
    pagination.total = response.total || 0;
    pagination.current = response.current_page || 1;
    
    console.log('✅ 数据更新成功:', {
      count: dataSource.value.length,
      total: pagination.total,
      current: pagination.current
    });
  } catch (error) {
    console.error('❌ 请求失败:', error);
    message.error('网络请求失败，请稍后重试');
    dataSource.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 搜索操作
const handleSearch = () => {
  pagination.current = 1; // 重置到第一页
  fetchData();
};

// 重置搜索条件
const handleReset = () => {
  searchForm.name = '';
  searchForm.phone = '';
  searchForm.id_card = '';
  pagination.current = 1; // 重置到第一页
  sortField.value = 'name';
  sortOrder.value = 'asc';
  fetchData();
};

// 导出数据（暂时占位）
const handleExport = () => {
  message.info('导出功能开发中...');
};

// 查看详情
const handleViewDetail = (id: number) => {
  message.info(`查看详情 ID: ${id}，功能开发中...`);
};

// 分页变化处理
const handleTableChange = (paginationParams: any, _filters: any, sorter: any) => {
  pagination.current = paginationParams.current;
  pagination.pageSize = paginationParams.pageSize;

  const field = sorter?.field as string | undefined;
  if (field && ['name', 'phone', 'status', 'created_at'].includes(field)) {
    sortField.value = field as typeof sortField.value;
  } else if (!sorter?.order) {
    sortField.value = 'name';
  }

  if (sorter?.order) {
    sortOrder.value = sorter.order === 'descend' ? 'desc' : 'asc';
  } else if (!sorter?.order) {
    sortOrder.value = 'asc';
  }

  fetchData();
};

// 组件挂载时加载数据
onMounted(() => {
  fetchData();
});
</script>

<template>
  <div class="p-5">
    <Card title="自由职业者管理">
      <!-- 搜索区域 -->
      <div class="mb-4">
        <Form layout="inline" :model="searchForm">
          <Form.Item label="姓名" name="name">
            <Input
              v-model:value="searchForm.name"
              placeholder="请输入姓名"
              style="width: 160px"
              allowClear
              @pressEnter="handleSearch"
            />
          </Form.Item>
          
          <Form.Item label="手机号" name="phone">
            <Input
              v-model:value="searchForm.phone"
              placeholder="请输入手机号"
              style="width: 160px"
              allowClear
              @pressEnter="handleSearch"
            />
          </Form.Item>
          
          <Form.Item label="身份证号" name="id_card">
            <Input
              v-model:value="searchForm.id_card"
              placeholder="请输入身份证号"
              style="width: 180px"
              allowClear
              @pressEnter="handleSearch"
            />
          </Form.Item>
          
          <Form.Item>
            <Space>
              <Button 
                type="primary" 
                @click="handleSearch"
                :loading="loading"
              >
                查询
              </Button>
              <Button @click="handleReset">
                重置
              </Button>
              <Button @click="handleExport">
                导出数据
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
      
      <!-- 数据表格 -->
      <Table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        :scroll="{ x: 1200 }"
        @change="handleTableChange"
      />
    </Card>
  </div>
</template>

<style scoped>
.ant-table-tbody > tr > td {
  padding: 12px 8px;
}

.ant-form-item {
  margin-bottom: 16px;
}
</style>
